package com.ztt.service;

import java.io.File;
import java.util.ArrayList;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.ztt.Config;
import com.ztt.model.FirstThumbModel;
import com.ztt.model.ProductDetailsModel;
import com.ztt.model.ThumbHeadModel;
import com.ztt.utils.HTTPUtils;
import com.ztt.utils.ImageUtils;

/**
 * 数据爬虫服务类
 * 
 * @author apple
 * 
 */
public class AnalyticalDataGoodsService {
	private String mUrl;
	private ProductDetailsModel mProductDetailsModel;

	public AnalyticalDataGoodsService(String pUrl) {
		this.mUrl = pUrl;
	}

	public ProductDetailsModel getDataService() throws Exception {
		mProductDetailsModel = new ProductDetailsModel();
		// 根节点
		Document mDocument = Jsoup.connect(mUrl).timeout(100000).get();
		// 商品名称-标题
		Element cont1_2_Element = mDocument.select("div.cont1-2").first();
		String prodname = cont1_2_Element.select("div.prodname").first().text()
				.trim();
		mProductDetailsModel.setProdname(prodname);
		// 商品价格
		String pro_tit = cont1_2_Element.select("div.pro-tit").first().text()
				.trim();
		mProductDetailsModel.setPro_tit(pro_tit);
		// VIP价格
		Element jpElement = cont1_2_Element.select("div.pro-jg").get(1)
				.select("div.jg").first();
		String vipprice = jpElement.getElementsByClass("viprice").get(0).text();
		mProductDetailsModel.setVipprice(vipprice);
		// 进行抓取顶部画廊图片
		getHeadImage(mProductDetailsModel, mDocument);
		// 开始进行抓取详情数据
		getGoodsDetails(mProductDetailsModel, mDocument);
		System.out.println(mProductDetailsModel);
		return mProductDetailsModel;
	}

	/**
	 * 进行抓取商品上不画廊图片 原图以及缩略图
	 * 
	 * @param mProductDetailsModel
	 *            //图片命名已经文文件夹命名规格
	 *            ///Storage/master/product/images/7652ea8d7a2d4336a40320db74f03
	 *            9 7 5 . j p g ///Storage/master/product/thumbs40/
	 *            40_7652ea8d7a2d4336a40320db74f03975.jpg
	 * @throws Exception
	 */
	private void getHeadImage(ProductDetailsModel mProductDetailsModel,
			Document pDocument) throws Exception {
		Elements thumb = pDocument.select("div.cont1-1").first()
				.select("div.thumb").first().getElementsByTag("li");
		if (thumb != null && thumb.size() > 0) {
			ThumbHeadModel mThumbHeadModel = new ThumbHeadModel();
			FirstThumbModel mFirstThumbModel = new FirstThumbModel();
			// 进行遍历取出所有图片
			for (int i = 0; i < thumb.size(); i++) {
				String img = thumb.get(i).getElementsByTag("img").get(0)
						.attr("data_url");
				String resultImg = deletePrefixLine(img);
				String fileName = System.currentTimeMillis()
						+ img.substring(img.lastIndexOf("."));
				System.out.println(resultImg + "\n进行原图下载中...");
				// 下载原图
				// 原图路径 --绝对路径
				String localURL = downLoadImage(resultImg, fileName,
						Config.ROOT_PATH + Config.IMAGE_DIRECTORY
								+ Config.IMAGE_ORIGINAL);
				// 原图路径 相对路径
				String original_path = Config.IMAGE_DIRECTORY
						+ Config.IMAGE_ORIGINAL + "/" + fileName;
				System.out.println("原图下载成功...\n" + "服务器地址:" + localURL);
				// 进行下载缩略图thumbs40
				String filename_thumbs40 = "40_" + fileName;
				File path_thumbs40 = new File(Config.PATH
						+ Config.IMAGE_THUMBNAIL_40);
				if (!path_thumbs40.exists()) {
					path_thumbs40.mkdir();
				}
				ImageUtils.saveImageAsJpg(localURL,
						path_thumbs40.getAbsolutePath() + "/"
								+ filename_thumbs40, 40, 40, true);
				// 进行下载缩略图thumbs60
				String filename_thumbs60 = "60_" + fileName;
				File path_thumbs60 = new File(Config.PATH
						+ Config.IMAGE_THUMBNAIL_60);
				if (!path_thumbs60.exists()) {
					path_thumbs60.mkdir();
				}
				ImageUtils.saveImageAsJpg(localURL,
						path_thumbs60.getAbsolutePath() + "/"
								+ filename_thumbs60, 60, 60, true);
				// 进行下载缩略图thumbs100
				String filename_thumbs100 = "100_" + fileName;
				File path_thumbs100 = new File(Config.PATH
						+ Config.IMAGE_THUMBNAIL_100);
				if (!path_thumbs100.exists()) {
					path_thumbs100.mkdir();
				}
				ImageUtils.saveImageAsJpg(localURL,
						path_thumbs100.getAbsolutePath() + "/"
								+ filename_thumbs100, 100, 100, true);
				// 进行下载缩略图thumbs160
				String filename_thumbs160 = "160_" + fileName;
				File path_thumbs160 = new File(Config.PATH
						+ Config.IMAGE_THUMBNAIL_160);
				if (!path_thumbs160.exists()) {
					path_thumbs160.mkdir();
				}
				ImageUtils.saveImageAsJpg(localURL,
						path_thumbs160.getAbsolutePath() + "/"
								+ filename_thumbs160, 160, 160, true);
				// 进行下载缩略图thumbs180
				String filename_thumbs180 = "180_" + fileName;
				File path_thumbs180 = new File(Config.PATH
						+ Config.IMAGE_THUMBNAIL_180);
				if (!path_thumbs180.exists()) {
					path_thumbs180.mkdir();
				}
				ImageUtils.saveImageAsJpg(localURL,
						path_thumbs180.getAbsolutePath() + "/"
								+ filename_thumbs180, 180, 180, true);
				// 进行下载缩略图thumbs220
				String filename_thumbs220 = "220_" + fileName;
				File path_thumbs220 = new File(Config.PATH
						+ Config.IMAGE_THUMBNAIL_220);
				if (!path_thumbs220.exists()) {
					path_thumbs220.mkdir();
				}
				ImageUtils.saveImageAsJpg(localURL,
						path_thumbs220.getAbsolutePath() + "/"
								+ filename_thumbs220, 220, 220, true);
				// 进行下载缩略图thumbs310
				String filename_thumbs310 = "310_" + fileName;
				File path_thumbs310 = new File(Config.PATH
						+ Config.IMAGE_THUMBNAIL_310);
				if (!path_thumbs310.exists()) {
					path_thumbs310.mkdir();
				}
				ImageUtils.saveImageAsJpg(localURL,
						path_thumbs310.getAbsolutePath() + "/"
								+ filename_thumbs310, 310, 310, true);
				// 进行下载缩略图thumbs410
				String filename_thumbs410 = "410_" + fileName;
				File path_thumbs410 = new File(Config.PATH
						+ Config.IMAGE_THUMBNAIL_410);
				if (!path_thumbs410.exists()) {
					path_thumbs410.mkdir();
				}
				ImageUtils.saveImageAsJpg(localURL,
						path_thumbs410.getAbsolutePath() + "/"
								+ filename_thumbs410, 410, 410, true);
				// 进行存储商品详情 原图
				if (i == 0) {
					mThumbHeadModel.setOriginal_one(original_path);
					// 进行添加第一张原图的各种缩略图
					mFirstThumbModel.setFirstThumb_one(Config.IMAGE_DIRECTORY
							+ "/" + filename_thumbs40);
					mFirstThumbModel.setFirstThumb_two(Config.IMAGE_DIRECTORY
							+ "/" + filename_thumbs60);
					mFirstThumbModel.setFirstThumb_three(Config.IMAGE_DIRECTORY
							+ "/" + filename_thumbs100);
					mFirstThumbModel.setFirstThumb_four(Config.IMAGE_DIRECTORY
							+ "/" + filename_thumbs160);
					mFirstThumbModel.setFirstThumb_five(Config.IMAGE_DIRECTORY
							+ "/" + filename_thumbs180);
					mFirstThumbModel.setFirstThumb_six(Config.IMAGE_DIRECTORY
							+ "/" + filename_thumbs220);
					mFirstThumbModel.setFirstThumb_seven(Config.IMAGE_DIRECTORY
							+ "/" + filename_thumbs310);
					mFirstThumbModel.setFirstThumb_eight(Config.IMAGE_DIRECTORY
							+ "/" + filename_thumbs410);
				} else if (i == 1) {
					mThumbHeadModel.setOriginal_two(original_path);
				} else if (i == 2) {
					mThumbHeadModel.setOriginal_three(original_path);
				} else if (i == 3) {
					mThumbHeadModel.setOriginal_four(original_path);
				} else if (i == 4) {
					mThumbHeadModel.setOriginal_five(original_path);
				}
			}
			mProductDetailsModel.setThumbHeadModel(mThumbHeadModel);
			mProductDetailsModel.setFirstThumbModel(mFirstThumbModel);
		}
	}

	/**
	 * 根据原图的地址，进行下载图片并且进行尺寸压缩处理,然后返回图片在服务器的相对路径
	 * 
	 * @param pResultImg
	 *            原图的地址
	 * @param folder
	 *            存放图片的文件夹
	 * @return 
	 *         /Storage/master/product/images/7652ea8d7a2d4336a40320db74f03975.jp
	 *         g
	 *         /Storage/master/product/thumbs40/40_7652ea8d7a2d4336a40320db74f03
	 *         9 7 5 . j p g
	 */
	private String downLoadImage(String pResultImg, String pFileName,
			String path) {
		String localPath = ""; // 本地服务器图片的地址(相对地址)
		byte[] btImg = HTTPUtils.getImageFromNetByUrl(pResultImg);
		if (null != btImg && btImg.length > 0) {
			System.out.println("读取到：" + btImg.length + " 字节");
			// 进行保存到本地
			boolean result = HTTPUtils.writeImageToDisk(btImg, pFileName, path);
			if (result) {
				localPath = path + "/" + pFileName;
			} else {
				// 如果保存失败直接返回""
				localPath = "";
			}
		} else {
			System.out.println("没有从该连接获得内容");
		}
		return localPath;
	}

	/**
	 * 根据HTML 文档进行抓取商品详情数据，并且并且把其他的数据进行下载，然后进行处理，保存一份PC HTML代码以及一份Mobile HTML代码
	 * 
	 * @time 2014、11、19 21：27新增适配手机端640 去掉width以及height标签的手机端代码
	 * 
	 * @param pProductDetailsModel
	 * @param pDocument
	 * @throws Exception
	 */
	private void getGoodsDetails(ProductDetailsModel pProductDetailsModel,
			Document pDocument) throws Exception {
		Element element_goodDetails = pDocument.select("div.li_spxq_a_con")
				.first();
		String mDetails = element_goodDetails.toString();
		System.out.println("商品详情:\n" + element_goodDetails);
		Elements elements_img = element_goodDetails.getElementsByTag("img");
		ArrayList<String[]> mURLLists = new ArrayList<String[]>();
		ArrayList<String> mURLs = new ArrayList<String>();
		for (Element element : elements_img) {
			String src = element.attr("src");
			mURLs.add(src);
			mURLLists.add(getGoodsDetailsImage(src));
		}
		// 进行生成PC HTML格式
		String mPC_Details = mDetails;
		for (int i = 0; i < elements_img.size(); i++) {
			String[] mPCURL = mURLLists.get(i);
			mPC_Details = mPC_Details.replace(mURLs.get(i), mPCURL[0]);
		}
		// 进行生成Mobile HTML格式
		String mMobile_Details = mDetails;
		for (int i = 0; i < elements_img.size(); i++) {
			String[] mPCURL = mURLLists.get(i);
			mMobile_Details = mMobile_Details.replace(mURLs.get(i), mPCURL[1]);
		}
		mMobile_Details = mMobile_Details.replaceAll(
				"width\\s*=\\s*\"[^\"]+\"", "").replaceAll(
				"height\\s*=\\s*\"[^\"]+\"", "");
		System.out.println("mMobile_Details:" + mMobile_Details);
		// 进行生成Mobile 640并且去掉width以及height属性 HTML格式适配手机端
		String mMobile_Details_640 = mDetails;
		for (int i = 0; i < elements_img.size(); i++) {
			String[] mPCURL = mURLLists.get(i);
			mMobile_Details_640 = mMobile_Details_640.replace(mURLs.get(i),
					mPCURL[2]);
		}
		mMobile_Details_640 = mMobile_Details_640.replaceAll(
				"width\\s*=\\s*\"[^\"]+\"", "").replaceAll(
				"height\\s*=\\s*\"[^\"]+\"", "");
		System.out.println("mMobile_Details_640:" + mMobile_Details_640);
		// 进行生成Mobile 600并且去掉width以及height属性 HTML格式适配手机端
		String mMobile_Details_600 = mDetails;
		for (int i = 0; i < elements_img.size(); i++) {
			String[] mPCURL = mURLLists.get(i);
			mMobile_Details_600 = mMobile_Details_600.replace(mURLs.get(i),
					mPCURL[3]);
		}
		mMobile_Details_600 = mMobile_Details_600.replaceAll(
				"width\\s*=\\s*\"[^\"]+\"", "").replaceAll(
				"height\\s*=\\s*\"[^\"]+\"", "");
		System.out.println("mMobile_Details_600:" + mMobile_Details_600);
		// 进行生成Mobile 580并且去掉width以及height属性 HTML格式适配手机端
		String mMobile_Details_580 = mDetails;
		for (int i = 0; i < elements_img.size(); i++) {
			String[] mPCURL = mURLLists.get(i);
			mMobile_Details_580 = mMobile_Details_580.replace(mURLs.get(i),
					mPCURL[4]);
		}
		mMobile_Details_580 = mMobile_Details_580.replaceAll(
				"width\\s*=\\s*\"[^\"]+\"", "").replaceAll(
				"height\\s*=\\s*\"[^\"]+\"", "");
		System.out.println("mMobile_Details_580:" + mMobile_Details_580);
		// 进行生成Mobile 550并且去掉width以及height属性 HTML格式适配手机端
		String mMobile_Details_550 = mDetails;
		for (int i = 0; i < elements_img.size(); i++) {
			String[] mPCURL = mURLLists.get(i);
			mMobile_Details_550 = mMobile_Details_550.replace(mURLs.get(i),
					mPCURL[5]);
		}
		mMobile_Details_550 = mMobile_Details_550.replaceAll(
				"width\\s*=\\s*\"[^\"]+\"", "").replaceAll(
				"height\\s*=\\s*\"[^\"]+\"", "");
		System.out.println("mMobile_Details_550:" + mMobile_Details_550);

		// 进行保存详情HTML数据
		pProductDetailsModel.setGoodDetailsPC(mPC_Details);
		pProductDetailsModel.setGoodDetailsMobile(mMobile_Details);
		pProductDetailsModel.setGoodDetailsMobile640(mMobile_Details_640);
		pProductDetailsModel.setGoodDetailsMobile600(mMobile_Details_600);
		pProductDetailsModel.setGoodDetailsMobile580(mMobile_Details_580);
		pProductDetailsModel.setGoodDetailsMobile550(mMobile_Details_550);
	}

	private String[] getGoodsDetailsImage(String pUrl) throws Exception {
		// 定义一个数组进行接收原图以及Mobile图片的路径
		String[] mUrls = new String[6]; // 第三项是为640的图片地址 第四项600 ,第五项580 ，第六项550
		if(isImage(pUrl)){
			//标准图片地址
		String fileName = System.currentTimeMillis()
				+ pUrl.substring(pUrl.lastIndexOf("."));
		System.out.println(pUrl + "\n进行原图下载中...");
		// 商品详情原图路径
		String goodDetailsLocalURL = downLoadImage(pUrl, fileName,
				Config.ROOT_PATH + Config.IMAGE_DIRECTORY
						+ Config.IMAGE_ORIGINAL_GOOD_DETAILS);
		// 进行处理手机端图片
		String filename_thumbs320 = "320_" + fileName;
		File path_thumbs320 = new File(Config.PATH
				+ Config.IMAGE_ORIGINAL_GOOD_DETAILS_320);
		if (!path_thumbs320.exists()) {
			path_thumbs320.mkdir();
		}
		ImageUtils.saveImageAsJpg(goodDetailsLocalURL,
				path_thumbs320.getAbsolutePath() + "/" + filename_thumbs320,
				320, 0, false);
		// 进行处理手机端图片 640宽度
		String filename_thumbs640 = "640_" + fileName;
		File path_thumbs640 = new File(Config.PATH
				+ Config.IMAGE_ORIGINAL_GOOD_DETAILS_640);
		if (!path_thumbs640.exists()) {
			path_thumbs640.mkdir();
		}
		ImageUtils.saveImageAsJpg(goodDetailsLocalURL,
				path_thumbs640.getAbsolutePath() + "/" + filename_thumbs640,
				640, 0, false);
		// 进行处理手机端图片 600宽度
		String filename_thumbs600 = "600_" + fileName;
		File path_thumbs600 = new File(Config.PATH
				+ Config.IMAGE_ORIGINAL_GOOD_DETAILS_600);
		if (!path_thumbs600.exists()) {
			path_thumbs600.mkdir();
		}
		ImageUtils.saveImageAsJpg(goodDetailsLocalURL,
				path_thumbs600.getAbsolutePath() + "/" + filename_thumbs600,
				600, 0, false);
		// 进行处理手机端图片 580宽度
		String filename_thumbs580 = "580_" + fileName;
		File path_thumbs580 = new File(Config.PATH
				+ Config.IMAGE_ORIGINAL_GOOD_DETAILS_580);
		if (!path_thumbs580.exists()) {
			path_thumbs580.mkdir();
		}
		ImageUtils.saveImageAsJpg(goodDetailsLocalURL,
				path_thumbs580.getAbsolutePath() + "/" + filename_thumbs580,
				580, 0, false);
		// 进行处理手机端图片 550宽度
		String filename_thumbs550 = "550_" + fileName;
		File path_thumbs550 = new File(Config.PATH
				+ Config.IMAGE_ORIGINAL_GOOD_DETAILS_550);
		if (!path_thumbs550.exists()) {
			path_thumbs550.mkdir();
		}
		ImageUtils.saveImageAsJpg(goodDetailsLocalURL,
				path_thumbs550.getAbsolutePath() + "/" + filename_thumbs550,
				550, 0, false);

		mUrls[0] = Config.IMAGE_DIRECTORY + Config.IMAGE_ORIGINAL_GOOD_DETAILS
				+ "/" + fileName; // 原图路径
		mUrls[1] = Config.IMAGE_DIRECTORY
				+ Config.IMAGE_ORIGINAL_GOOD_DETAILS_320 + "/"
				+ filename_thumbs320; // Mobile专用图片路径
		mUrls[2] = Config.IMAGE_DIRECTORY
				+ Config.IMAGE_ORIGINAL_GOOD_DETAILS_640 + "/"
				+ filename_thumbs640; // Mobile专用图片路径 640
		mUrls[3] = Config.IMAGE_DIRECTORY
				+ Config.IMAGE_ORIGINAL_GOOD_DETAILS_600 + "/"
				+ filename_thumbs600; // Mobile专用图片路径 600
		mUrls[4] = Config.IMAGE_DIRECTORY
				+ Config.IMAGE_ORIGINAL_GOOD_DETAILS_580 + "/"
				+ filename_thumbs580; // Mobile专用图片路径 580
		mUrls[5] = Config.IMAGE_DIRECTORY
				+ Config.IMAGE_ORIGINAL_GOOD_DETAILS_550 + "/"
				+ filename_thumbs550; // Mobile专用图片路径 550
		}else {
			//非标准图片地址URL 例如:http://pic.taocz.com/store_1331156286/goods_127/201203081648473097.jpeg?q=12333
		    for(int i=0;i<mUrls.length;i++){
		    	mUrls[i]=pUrl;
		    }
		}
		return mUrls;
	}

	/**
	 * 进行地址转换处理，获取原图地址 例如:http://pic.taocz.com/store_1331156286/goods_127/
	 * small_201203081648473097.jpeg -->
	 * http://pic.taocz.com/store_1331156286/goods_127/201203081648473097.jpeg
	 * 
	 * @param pUrlStr
	 * @return
	 */
	private String deletePrefixLine(String pUrlStr) {
		int beginIndex = pUrlStr.lastIndexOf("/");
		int endIndex = pUrlStr.lastIndexOf("_");
		StringBuffer sbBuffer = new StringBuffer(pUrlStr.substring(0,
				beginIndex + 1));
		sbBuffer.append(pUrlStr.substring(endIndex + 1));
		return sbBuffer.toString();
	}

	/**
	 * 进行本地服务器 文件存放地址 路径目录
	 */
	public void createDirectory() {
		File rootPath = new File(Config.ROOT_PATH);
		if (!rootPath.exists()) {
			rootPath.mkdirs();
		}
		if (rootPath.exists()) {
			File image_directory = new File(rootPath, Config.IMAGE_DIRECTORY);
			if (!image_directory.exists()) {
				image_directory.mkdirs();
			}

		}
	}

	/**
	 * 判断地址是否是以.png,.PNG,.jpg,.JPG,.JPEG,jpeg, .jpg .jpeg .gif .png .bmp图片格式转换
	 * 判断是否是正确的图片地址
	 * @param pImageURL
	 * @return
	 */
	private boolean isImage(String pImageURL) {
		if (pImageURL.endsWith("png") || pImageURL.endsWith("PNG")
				|| pImageURL.endsWith("jpg") || pImageURL.endsWith("JPG")
				|| pImageURL.endsWith("jpeg") || pImageURL.endsWith("JPEG")
				|| pImageURL.endsWith("gif") || pImageURL.endsWith("GIF")
				|| pImageURL.endsWith("bmp") || pImageURL.endsWith("BMP")) {
			return true;
		}
		return false;
	}

	/**
	 * width\\s*=\\s*\"[^\"]+\"
	 * 
	 * @return
	 */
	private String deleteWidth() {

		return null;
	}
}
